﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GabageFactory.Models;
using System.IO;

namespace GabageFactory.Controllers
{
    [HandleError]
    public class BaseController : Controller
    {
        public enum FileType
        {
            Image,
            Doc,
            Reporting,
            ReportingImage,
            Event
        }
        
        //
        // GET: /Base/

        protected ActionResult AllowForRole(RoleEnum role)
        {
            if (!FormsAuthenticationService.IsInRole(role))
            {
                return RedirectToAction("Deny", "Home");
            }

            return null;
        }

        protected ActionResult AllowForRole(List<RoleEnum> roles)
        {
            foreach(RoleEnum role in roles)
            {
                if (FormsAuthenticationService.IsInRole(role))
                {
                    return null;
                }
            }

            return RedirectToAction("Deny", "Home");
        }

        protected User GetCurrentUser()
        {
            return FormsAuthenticationService.GetCurrentUser();
        }

        protected void ShowFactoryList(long factoryId, bool addAllOption = false)
        {
            FactoryReposity factoryReposity = new FactoryReposity();
            List<SelectListItem> factories = new List<SelectListItem>();
            if (addAllOption)
            {

                factories.Add(new SelectListItem { Text = "全部", Value = "0", Selected = false });
            }
            foreach (Factory f in factoryReposity.ListFactories())
            {
                bool selected = false;
                if (factoryId == f.Id)
                {
                    selected = true;
                }
                factories.Add(new SelectListItem { Text = f.Name, Value = f.Id.ToString(), Selected = selected });
            }
            ViewData["factories"] = factories;
        }

        protected void ShowStackAndTailingoind(long factoryId, int showType = 0, int selectedId = 0, int type = 0)
        {
            List<SelectListItem> values = new List<SelectListItem>();
            StackReposity stackReposity = new StackReposity();
            TailingpondReposity tailingpondReposity = new TailingpondReposity();
            if (showType == 0)
            {
                foreach (Stack s in stackReposity.QueryStacks(null, (int)factoryId))
                {
                    values.Add(new SelectListItem { Text = s.Name, Value = "0-" + s.Id, Selected = (type == 0 && selectedId == s.Id) });
                }


                foreach (Tailingpond t in tailingpondReposity.QueryTailingponds((int)factoryId, null))
                {
                    values.Add(new SelectListItem { Text = t.Name, Value = "1-" + t.Id, Selected = (type == 1 && selectedId == t.Id) });
                }
            }
            else if (showType == 1)
            {
                foreach (Stack s in stackReposity.QueryStacks(null, (int)factoryId))
                {
                    values.Add(new SelectListItem { Text = s.Name, Value = s.Id.ToString(), Selected = (selectedId == s.Id) });
                }
            }
            else if (showType == 2)
            {
                foreach (Tailingpond t in tailingpondReposity.QueryTailingponds((int)factoryId, null))
                {
                    values.Add(new SelectListItem { Text = t.Name, Value = t.Id.ToString(), Selected = (selectedId == t.Id) });
                }
            }
            ViewData["stacksAndTailingponds"] = values;
        }

        protected void ShowUserList(long factoryId, RoleEnum role, long? userId)
        {
            UserReposity userReposity = new UserReposity();
            List<SelectListItem> users = new List<SelectListItem>();
            
            foreach (User u in userReposity.QueryUsers(null, (int)role, (int)factoryId))
            {
                bool selected = false;
                if (userId.HasValue && userId.Value == u.Id)
                {
                    selected = true;
                }
                users.Add(new SelectListItem { Text = u.RealName + "(" + u.Name + ")", Value = u.Id.ToString(), Selected = selected });
            }
            ViewData["users"] = users;
        }

        protected void ShowRoleList(long roleId)
        {
            RoleReposity roleReposity = new RoleReposity();
            List<SelectListItem> roles = new List<SelectListItem>();
            foreach (Role r in roleReposity.ListRoles())
            {
                bool selected = false;
                if (roleId == r.Id)
                {
                    selected = true;
                }
                roles.Add(new SelectListItem { Text = r.Name, Value = r.Id.ToString(), Selected = selected });
            }
            ViewData["roles"] = roles;
        }

        protected void ShowPositionList(int position)
        {
            List<SelectListItem> roles = new List<SelectListItem>();
            roles.Add(new SelectListItem { Text = "东", Value = "1", Selected = position == 1 });
            roles.Add(new SelectListItem { Text = "东南", Value = "2", Selected = position == 2 });
            roles.Add(new SelectListItem { Text = "南", Value = "3", Selected = position == 3 });
            roles.Add(new SelectListItem { Text = "西南", Value = "4", Selected = position == 4 });
            roles.Add(new SelectListItem { Text = "西", Value = "5", Selected = position == 5 });
            roles.Add(new SelectListItem { Text = "西北", Value = "6", Selected = position == 6 });
            roles.Add(new SelectListItem { Text = "北", Value = "7", Selected = position == 7 });
            roles.Add(new SelectListItem { Text = "东北", Value = "8", Selected = position == 8 });
            
            ViewData["roles"] = roles;
        }

        protected void ShowFactoryAndRoleList(User user)
        {
            long factoryId = 0, roleId = 0;
            if (user != null)
            {
                factoryId = user.FactoryId;
                roleId = user.RoleId;
            }
            ShowFactoryList(factoryId);
            ShowRoleList(roleId);
        }


        protected int parseInt(string value)
        {
            int result = 0;
            try
            {
                result = int.Parse(value);
            }
            catch
            {
                // empty
            }

            return result;
        }

        protected float parseFloat(string value)
        {
            float result = 0;
            try
            {
                result = float.Parse(value);
            }
            catch
            {
                // empty
            }

            return result;
        }

        protected void ParseSid(string stackId, ref int id, ref int stype)
        {
            if (!string.IsNullOrEmpty(stackId))
            {
                string[] values = stackId.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                if (values.Length == 2)
                {
                    stype = int.Parse(values[0]);
                    id = int.Parse(values[1]);
                }
            }
        }

        protected string UploadFile(HttpPostedFileBase file, FileType fileType = FileType.Image)
        {
            Random random = new Random();
            var fileName = DateTime.Now.Millisecond.ToString() + random.Next(100000).ToString() + Path.GetFileName(file.FileName);
            var path = "";
            var returnFile = "";
            if (fileType == FileType.Image)
            {
                path = Path.Combine(Server.MapPath("~/Upload/Images"), fileName);
                returnFile = "~/Upload/Images/" + fileName;
            }
            else if (fileType == FileType.Doc)
            {
                path = Path.Combine(Server.MapPath("~/Upload/Docs"), fileName);
                returnFile = "~/Upload/Docs/" + fileName;
            }
            else if (fileType == FileType.Reporting)
            {
                path = Path.Combine(Server.MapPath("~/Upload/Reportings"), fileName);
                returnFile = "~/Upload/Reportings/" + fileName;
            }
            else if (fileType == FileType.ReportingImage)
            {
                path = Path.Combine(Server.MapPath("~/Upload/Reportings/Images"), fileName);
                returnFile = "~/Upload/Reportings/Images/" + fileName;
            }
            else if (fileType == FileType.Event)
            {
                path = Path.Combine(Server.MapPath("~/Upload/Events"), fileName);
                returnFile = "~/Upload/Events/" + fileName;
            }
            file.SaveAs(path);

            return returnFile;
        }

    }
}
